﻿( 
   01 SEP 2013
   SPELLNUMBER ( n -- ) 
   Spell numbers up to 999 trillion using recursion. 

   James Larson
   Programmer/Analyst Consultant
   http://www.dst-corp.com/james
   mailto:jlarson43@juno.com
   http://www.dst-corp.com/james/JonesForthInC/SPELLNUMBER.f.txt

   In God We Trust...
)

: SPELLDIGIT CASE 
  1 OF ." ONE " ENDOF
  2 OF ." TWO " ENDOF
  3 OF ." THREE " ENDOF
  4 OF ." FOUR " ENDOF
  5 OF ." FIVE " ENDOF
  6 OF ." SIX " ENDOF
  7 OF ." SEVEN " ENDOF
  8 OF ." EIGHT " ENDOF
  9 OF ." NINE " ENDOF
  10 OF ." TEN " ENDOF
  11 OF ." ELEVEN " ENDOF
  12 OF ." TWELVE " ENDOF
  13 OF ." THIRTEEN " ENDOF
  14 OF ." FOURTEEN " ENDOF
  15 OF ." FIFTEEN " ENDOF
  16 OF ." SIXTEEN " ENDOF
  17 OF ." SEVENTEEN " ENDOF
  18 OF ." EIGHTEEN " ENDOF
  19 OF ." NINETEEN " ENDOF
  ENDCASE ;
: SPELLTENS CASE 
  2 OF ." TWENTY " ENDOF
  3 OF ." THIRTY " ENDOF
  4 OF ." FOURTY " ENDOF
  5 OF ." FIFTY " ENDOF
  6 OF ." SIXTY " ENDOF
  7 OF ." SEVENTY " ENDOF
  8 OF ." EIGHTY " ENDOF
  9 OF ." NINETY " ENDOF
  ENDCASE ;
: SPELLDECADE CASE 
  1 OF ." THOUSAND " ENDOF
  2 OF ." MILLION " ENDOF
  3 OF ." BILLION " ENDOF
  4 OF ." TRILLION " ENDOF
  ENDCASE ;
 0 VALUE _SPELL 
: _SPELLNUMBER 
   DUP ( n n ) 0< ( n f ) IF ( n ) NEGATE ( n ) ." MINUS " THEN 
   ( n ) 1000 /MOD ( r q )  DUP ( r q q ) 
   IF ( r q ) 1 +TO _SPELL RECURSE ( r ) 
      -1 +TO _SPELL ELSE ( r q ) DROP ( r ) THEN 
   ( r ) DUP ( r r ) 0= ( r f ) IF ( r ) DROP ( ) EXIT THEN 
   ( r ) 100 /MOD  ( r q ) DUP ( r q q ) 
   IF ( r q ) SPELLDIGIT ( r ) ." HUNDRED " ELSE ( r q ) DROP ( r ) THEN 
   ( r ) DUP ( r r ) 20 >= ( r f ) 
   IF ( r ) 10 /MOD ( r2 q ) SPELLTENS ( r2 ) ( ELSE ( r ) ) THEN 
   ( r ) SPELLDIGIT ( ) 
   _SPELL SPELLDECADE 
;
: SPELLNUMBER 
 ." SPELL: " DUP . CR 
   0 TO _SPELL 
   DUP ( n n ) 0= ( n f ) IF ( n ) DROP (  ) ." ZERO " EXIT ( ) THEN 
   ( n ) _SPELLNUMBER ( ) ; 
 .S CR
 1512 SPELLNUMBER CR 
 .S CR
 18512 SPELLNUMBER CR 
 .S CR
 318512 SPELLNUMBER CR 
 .S CR
 9318512 SPELLNUMBER CR 
 .S CR
 2000001 SPELLNUMBER CR 
 .S CR
 222000001 SPELLNUMBER CR 
 .S CR
 -1512 SPELLNUMBER CR 
 .S CR

